﻿using ICSharpCode.SharpZipLib.Zip;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;

namespace Gdmec.Util
{
    public class ZipUtil
    {

        private static void PackSub(string rootFP, string targetFP, ZipOutputStream zipOS, string search)
        {
            var files = Directory.GetFiles(targetFP, search);
            foreach (var file in files)
            {
                var file2 = PathUtil.ToSame(file.Substring(rootFP.Length + 1));
                ZipEntry entry = new ZipEntry(file2);
                entry.DateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
                zipOS.PutNextEntry(entry);
                var content = File.ReadAllBytes(file);
                zipOS.Write(content, 0, content.Length);
            }
            var dirs = Directory.GetDirectories(targetFP);
            foreach (var dir in dirs)
            {
                PackSub(rootFP, dir, zipOS, search);
            }
        }


        /// <summary>
        /// 解压Zip
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="outPath"></param>
        public static void UpZipByBytes(byte[] bytes, string outPath)
        {
            Encoding encode = new System.Text.UTF8Encoding(false);
            outPath = Path.GetFullPath(outPath);
            using (ZipInputStream decompressor = new ZipInputStream(new MemoryStream(bytes)))
            {
                ZipEntry entry;

                while ((entry = decompressor.GetNextEntry()) != null)
                {
                    string name = entry.Name;
                    if (entry.IsDirectory && entry.Name.StartsWith("\\"))
                        name = entry.Name.Replace("\\", "");

                    string filePath = Path.Combine(outPath, name);
                    string directoryPath = Path.GetDirectoryName(filePath);

                    if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath))
                        Directory.CreateDirectory(directoryPath);

                    if (entry.IsDirectory)
                        continue;

                    byte[] data = new byte[2048];
                    using (FileStream streamWriter = File.Create(filePath))
                    {
                        int bytesRead;
                        while ((bytesRead = decompressor.Read(data, 0, data.Length)) > 0)
                        {
                            streamWriter.Write(data, 0, bytesRead);
                        }
                    }
                }
            }
        }
    }
}
